package com.cmc.cloud.cmclink.doc.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaBaseQueryVo;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaBaseVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaCreateReqVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaExportReqVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaExportVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaHistoryVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaRespVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaStatusReqVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageBsaUpdateReqVO;
import com.cmc.cloud.cmclink.doc.vo.voyagebsavo.VoyageTemplateReqVO;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.excel.core.util.ExcelUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.servlet.http.HttpServletResponse;
import javax.validation.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;


import com.cmc.cloud.cmclink.doc.entity.VoyageBsaDO;
import com.cmc.cloud.cmclink.doc.service.VoyageBsaService;


/**
 * bsa （base space Allocation） 维护前端接口Controller
 *
 * @author codegen
 */
@Tag(name = "管理后台 - bsa （base space Allocation） 维护")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/bsa")
public class VoyageBsaController {

    @Resource
    private VoyageBsaService voyageBsaService;

    @Operation(summary = "创建bsa （base space Allocation） 维护")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:add','doc:setupBSAImport:add','doc:setupBSAExportTemplate:add','doc:setupBSAImportTemplate:add'})")
    public CommonResult<Void> createVoyageBsa(@Valid @RequestBody VoyageBsaCreateReqVO createReqVO) {
        voyageBsaService.createVoyageBsa(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新bsa （base space Allocation） 维护")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:edit','doc:setupBSAImport:edit','doc:setupBSAExportTemplate:edit','doc:setupBSAImportTemplate:edit'})")
    public CommonResult<Void> updateVoyageBsa(@Valid @RequestBody VoyageBsaUpdateReqVO updateReqVO) {
        voyageBsaService.updateVoyageBsa(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新bsa 开关舱状态")
    @PostMapping("/updateStatus")
    @PreAuthorize("@ss.hasPermission({'doc:spaceAllocation:bookingOpenStatus'})")
    public CommonResult<Void> updateOpenStatus(@Valid @RequestBody VoyageBsaStatusReqVO voyageBsaStatusReqVO) {
        voyageBsaService.updateOpenStatus(voyageBsaStatusReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "从历史数据复制hg,pod信息")
    @PostMapping("/copyFromHistory")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:copyAdd','doc:setupBSAImport:copyAdd','doc:setupBSAExportTemplate:copyAdd','doc:setupBSAImportTemplate:copyAdd','doc:spaceAllocation:copyAdd'})")
    public CommonResult<Void> copyFromHistory(@Valid @RequestBody VoyageBsaHistoryVO historyVo) {
        voyageBsaService.copyFromHistory(historyVo);
        return CommonResult.success();
    }

    @Operation(summary = "从历史数据复制cba信息")
    @PostMapping("/copyFromHistoryCba")
    public CommonResult<Void> copyFromHistoryCba(@Valid @RequestBody VoyageBsaHistoryVO historyVo) {
        voyageBsaService.copyFromHistoryCba(historyVo);
        return CommonResult.success();
    }

    @Operation(summary = "删除bsa （base space Allocation） 维护")
    @PostMapping("/delete/{id}")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:delete','doc:setupBSAImport:delete','doc:setupBSAExportTemplate:delete','doc:setupBSAImportTemplate:delete','doc:spaceAllocation:delete'})")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Void> deleteVoyageBsa(@PathVariable("id") Long id) {
        voyageBsaService.deleteVoyageBsa(id);
        return CommonResult.success();
    }

    @Operation(summary = "获得bsa （base space Allocation） 维护")
    @GetMapping("/get/{id}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<VoyageBsaRespVO> getVoyageBsa(@PathVariable("id") Long id) {
        VoyageBsaDO voyageBsa = voyageBsaService.getVoyageBsa(id);
        return CommonResult.success(BeanUtil.copyProperties(voyageBsa, VoyageBsaRespVO.class));
    }

    @Operation(summary = "获得bsa （base space Allocation） 维护列表")
    @GetMapping("/list")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<List<VoyageBsaRespVO>> getVoyageBsaList(@RequestParam("ids") Collection<Long> ids) {
        List<VoyageBsaDO> list = voyageBsaService.getVoyageBsaList(ids);
        return CommonResult.success(BeanUtil.copyToList(list, VoyageBsaRespVO.class));
    }

    @Operation(summary = "业务条件查询 获得bsa 维护列表")
    @PostMapping("/query")
    public CommonResult<List<VoyageBsaRespVO>> queryVoyageBsa(@Valid @RequestBody VoyageBsaBaseQueryVo bsaBaseQueryVo) {
        return CommonResult.success(voyageBsaService.queryVoyageBsa(bsaBaseQueryVo));
    }

    @Operation(summary = "获得bsa （base space Allocation） 维护分页")
    @PostMapping("/page")
    @UseResponsePropertyAdvice
    @PreAuthorize("@ss.hasPermission({'doc:spaceAllocation:search','doc:setupBSAExport:search','doc:setupBSAImport:search','doc:setupBSAExportTemplate:search','doc:SetupBSAImporttemplat:search','doc:planTemplate:search'})")
    public CommonResult<PageResult<VoyageBsaRespVO>> getVoyageBsaPage(@Valid @RequestBody VoyageBsaPageReqVO pageVO) {
        PageResult<VoyageBsaRespVO> pageResult = voyageBsaService.getVoyageBsaPage(pageVO);
        return CommonResult.success(pageResult);
    }

    @GetMapping("/excel-export")
    @Operation(summary = "excel导出")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:expport','doc:setupBSAImport:expport'})")
    @Parameter(name = "laneCode", description = "航线", required = true)
    @Parameter(name = "voyage", description = "航次")
    @Parameter(name = "vesselCode", description = "船舶代码")
    @Parameter(name = "startTime", description = "开始时间", required = true)
    @Parameter(name = "endTime", description = "结束时间", required = true)
    @Parameter(name = "isTemplate", description = "是否模板", required = true)
    @Parameter(name = "exImType", description = "进出口类型", required = true)
    public void exportExcelTemplate(HttpServletResponse response, @RequestParam(value = "laneCode") String laneCode
            , @RequestParam(value = "voyage") String voyage
            , @RequestParam(value = "vesselCode") String vesselCode
            , @RequestParam(value = "startTime") String startTime
            , @RequestParam(value = "endTime") String endTime
            , @RequestParam(value = "isTemplate") Boolean isTemplate
            , @RequestParam(value = "exImType") String exImType) throws IOException {
        VoyageBsaExportReqVO voyageBsaExportReqVO = VoyageBsaExportReqVO.builder().laneCode(laneCode).voyage(voyage).vesselCode(vesselCode).startTime(startTime).endTime(endTime).isTemplate(isTemplate).exImType(exImType).build();
        List<VoyageBsaExportVO> exportList = voyageBsaService.getExportList(voyageBsaExportReqVO);
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        StringBuilder sb = new StringBuilder();
        String fileName = sb.append("bsa_").append(System.currentTimeMillis()).append(".xlsx").toString();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, fileName, "模版", VoyageBsaExportVO.class, exportList);
    }

    @Operation(summary = "从模板数据 创建bsa")
    @PostMapping("/createFromTel")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:addByTemplate','doc:setupBSAImport:addByTemplate'})")
    public CommonResult<Void> createFromTemplate(@Valid @RequestBody VoyageTemplateReqVO templateReqVO) {
        voyageBsaService.createFromTemplate(templateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "获取已存在的航次列表")
    @PostMapping("/voyages")
    public CommonResult<List<String>> getExistVoyages(@Valid @RequestBody VoyageTemplateReqVO templateReqVO) {
        List<String> existVoyages = voyageBsaService.getExistVoyages(templateReqVO);
        return CommonResult.success(existVoyages);
    }

    @Operation(summary = "判断目前bsa 是否已存在 分类舱位的配置信息")
    @PostMapping("/assert")
    @PreAuthorize("@ss.hasPermission({'doc:spaceAllocation:copyHistory'})")
    public CommonResult<Boolean> assertBsaCbaExist(@Valid @RequestBody VoyageBsaBaseVO voyageBsaBaseVO) {
        return CommonResult.success(voyageBsaService.assertBsaCbaExist(voyageBsaBaseVO));
    }

    @Operation(summary = "收藏bsa为模板")
    @PostMapping("/collect/{id}")
    @PreAuthorize("@ss.hasPermission({'doc:setupBSAExport:like','doc:setupBSAImport:like','doc:setupBSAExportTemplate:like','doc:setupBSAImportTemplate:like'})")
    public CommonResult<Void> collect(@PathVariable("id") Long id) {
        voyageBsaService.collectBsaTemplate(id);
        return CommonResult.success();
    }

}
